package com.lagou.session;

import com.lagou.bean.Configuration;
import com.lagou.bean.MapperStatement;
import com.lagou.config.BoundSql;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    private Connection connection;
    @Override
    public <E> List<E> query(Configuration conf, MapperStatement stmt, Object[] params) throws Exception {
        PreparedStatement preparedStatement = this.preparedStatement(conf, stmt, params);
        //以下开始处理结果集
        Class<?> resultType = stmt.getResultType();
        List<E> results = new ArrayList<>();
        ResultSet rs = preparedStatement.executeQuery();
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        while (rs.next()) {
            E o = (E) resultType.newInstance();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                Object value = rs.getObject(columnName);
                PropertyDescriptor pd = new PropertyDescriptor(columnName, resultType);
                pd.getWriteMethod().invoke(o, value);
            }
            results.add(o);
        }

        return results;
    }

    public BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler();
        GenericTokenParser parser = new GenericTokenParser("#{", "}", handler);
        String text = parser.parse(sql);
        return new BoundSql(text, handler.getParameterMappings());
    }

    @Override
    public void close() throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }

    @Override
    public int update(Configuration conf, MapperStatement stmt, Object... params) throws Exception {
        PreparedStatement preparedStatement = this.preparedStatement(conf, stmt, params);
        return preparedStatement.executeUpdate();
    }

    PreparedStatement preparedStatement(Configuration conf, MapperStatement stmt, Object[] params) throws Exception {
        this.connection = conf.getDataSource().getConnection();
        String sql = stmt.getSql();
        BoundSql boundSql = this.getBoundSql(sql);
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        Class<?> paramterType = stmt.getParamterType();
        if (paramterType == null) {
            // 如果没有paramter,证明不需要设置参数
            return preparedStatement;
        }

        //以下开始设置参数
        List<ParameterMapping> list = boundSql.getParameterMappings();
        for (int i = 0; i< list.size(); i++) {
            String content = list.get(i).getContent();
            PropertyDescriptor pd = new PropertyDescriptor(content, paramterType);
            Object val = pd.getReadMethod().invoke(params[0]);
            preparedStatement.setObject(i+1, val);
        }
        return preparedStatement;
    }
}
